import Taro, { Config } from '@tarojs/taro'
import { Button, Image, RichText, Text, View } from '@tarojs/components'
import './index.scss'
import '@/styles/common/goods-info.scss'
import classNames from 'classnames'
import lodash from "@/utils/lodash"
import { GOODS_TYPE } from "@/config/types"
import { infoById } from '@/api/productApi'
import { filterGoodsInfo } from "@/utils/filter"
import { formatHtml, formatAmount} from "@/utils/utils"
import { getSharePath, verifyUserLogin } from '@/utils/storage'
import {toCalcOrderPage, toCalcVirtualOrder, toCommentGoodsPage, toUserLoginPage} from '@/utils/page_router'
import FyComponent from "@/components/common/goods"
import {
  GoodsNavbar,
  Loading,
  TitleOne,
  AvatarList,
  GoodsCarousel,
  GoodsOneList,
  ShareImage,
  CommentGoods,
  GoodsSelect,
  GroupsCountdown
} from "@/components/index"
import GroupJoin from "@/market/components/group-join/index"
import GoodsFoot from "@/components/goods/goods-foot"
import ShopInfoOne from "@/components/shop/info-one";
import ShopInfoTwo from "@/components/shop/info-two";

export default class Index extends FyComponent {
  isJoin: boolean
  config: Config = {
    navigationStyle: 'custom'
  }

  constructor() {
    super()
    this.isJoin = true
  }

  componentWillMount() {
    verifyUserLogin({
      fail: function () {
        toUserLoginPage()
      }
    })
    this.getGoodsInfo()
    this.getGoodsPage()
    this.getCommentPage()
  }

  componentDidShow () {
    //  已经加载完毕
    if (!this.state.loading) {
      this.setState({
        loading: true
      }, () => {
        this.updateGoods()
      })
    }
  }

  //  分享小程序
  onShareAppMessage() {
    const { pinkInfo, goodsInfo } = this.state
    const { path, params } = lodash.cloneDeep(this.$router)
    pinkInfo && (params.pinkId = pinkInfo.id)
    return { title: goodsInfo.name, path: getSharePath(path, params) }
  }

  //  获取商品详情
  getGoodsInfo() {
    let data:any = {}
    const { params } = this.$router
    params.pinkId && (data.pinkId = params.pinkId)
    infoById(params.id, data).then(({ data: { pinkInfo ,pinkConfig , ...info } }) => {
      if (pinkInfo) {
        const list:any = []
        const people = pinkInfo.totalNum - pinkInfo.currencyNum
        const users = pinkInfo.partakeList.map(user => user.headImg)
        for (let i=0; i<pinkInfo.totalNum; i++){
          list.push(users[i] ? users[i] : i)
        }
        pinkInfo.partakeList = list
        pinkInfo.people = people <= 0 ? 0 : people
      }
      info.timestamp = Number(new Date())
      this.setState({
        pinkInfo,
        pinkConfig,
        goodsInfo: filterGoodsInfo(info),
        comboList: info.skuDetail || [],
        goodsImages: info.images
      }, () => {
        this.setState({
          loading: false
        })

        setTimeout(() => {
          this.getNodeLocation()
        }, 200)

        if (pinkConfig.hasPart && pinkConfig.isSamePink) {
          setTimeout(() => {
            this.setState({
              showIsJoin: true
            })
          }, 1500)
        }
      })
    }).catch(err => {
      console.log(err)
      setTimeout(() => {
        wx.navigateBack()
      }, 800)
    })
  }

  //  更新商品信息
  updateGoods() {
    let data:any = {}
    const { params } = this.$router
    // const { pinkInfo, pinkConfig } = this.state
    params.pinkId && (data.pinkId = params.pinkId)
    infoById(params.id, data).then(({ data: { pinkInfo, pinkConfig } }) => {
      if (pinkInfo) {
        const users = pinkInfo.partakeList.map(user => user.headImg)
        const list:any = []
        for (let i=0; i<pinkInfo.totalNum; i++){
          list.push(users[i] ? users[i] : i)
        }
        pinkInfo.partakeList = list
        const people = pinkInfo.totalNum - pinkInfo.currencyNum
        pinkInfo.people = people <= 0 ? 0 : people
      }
      this.setState({
        pinkInfo,
        pinkConfig,
        loading: false
      }, () => {
        setTimeout(() => {
          this.getNodeLocation()
        }, 200)

        if (this.isJoin && pinkConfig.hasPart && pinkConfig.isSamePink) {
          setTimeout(() => {
            this.setState({
              showIsJoin: true
            })
          }, 1500)
        }
      })
    })
  }

  //  关闭已经加入的拼团
  onCloseJoin() {
    this.isJoin = false
    this.setState({
      showIsJoin: false
    })
  }

  //  显示选择商品
  setShowSelect(type) {
    this.setState({
      showSelect: type,
      replacePrice: type === 'group' ? 'salePrice' : 'originPrice'
    })
  }

  //  确认选择商品
  onConfirm(type, info, number) {
    const { params } = this.$router
    this.setState({
      showSelect: false
    })

    if (type === 'group') {
      if (info.type === GOODS_TYPE.VIRTUAL) {
        toCalcVirtualOrder({ id: info.productId, skuId: info.skuId, number, shopId: info.shopId, isPink: true, pinkId: params.pinkId })
      } else {
        toCalcOrderPage({
          isPink: true,
          pinkId: params.pinkId,
          cartList: [{ id: info.productId, skuId: info.skuId, number }]
        })
      }
    } else {
      if (info.type === GOODS_TYPE.VIRTUAL) {
        toCalcVirtualOrder({ id: info.productId, skuId: info.skuId, number, shopId: info.shopId, fullPay: 1 })
      } else {
        toCalcOrderPage({
          fullPay: 1,
          cartList: [{ id: info.productId, skuId: info.skuId, number }]
        })
      }
    }
  }

  render() {
    const { opacity, nodeKey, nodeList, goodsInfo, goodsList, showSelect, showShareImg, shareImg, commentRes, loading, replacePrice, pinkInfo, pinkConfig, showIsJoin } = this.state
    const salesReport = goodsInfo.salesReport && goodsInfo.salesReport.map(i => i.userInfo && i.userInfo.headImg)
    const percent:any = (100 / nodeList.length).toFixed(2)
    return (<View className='goods-page'>
      {loading && <Loading/>}
      <GoodsNavbar opacity={opacity}>
        <View className='node-list'>
          {nodeList.map((item, key) => {
            return (<View key={item.id} className={classNames('node-item f-g-5', nodeKey === key && 'node-item__active')} onClick={this.onSwitchNode.bind(this, item, key)}>{item.name}</View>)
          })}
          <View className='under-line' style={{ left: `calc(${nodeKey * percent}% + (${percent}% / 2))` }}/>
        </View>
      </GoodsNavbar>
      <View className='goods-scroll'>
        <View id='goods-info' className='goods-card'>
          <GoodsCarousel images={goodsInfo.images} video={{ url: goodsInfo.video, poster: goodsInfo.videoCoverImg }}/>
          <View className='goods-head'>
            <View className='d-f a-i-c j-c-b'>
              <View className='price d-f a-i-b'>
                <View className='sale-price bnn-number'><Text className='price-unit'>￥</Text>{goodsInfo.salePrice}</View>
                {goodsInfo.originPrice > goodsInfo.salePrice && <View className='origin-price bnn-number m-l-10'>￥{goodsInfo.originPrice}</View>}
              </View>
              <View className='user-like f-g-5'>
                <Text className='like-icon bnn-icon m-r-10'>&#xe668;</Text>{goodsInfo.storeCount}人喜欢
              </View>
            </View>
            <View className='goods-name'>{goodsInfo.name}</View>
            <View className='stock-box d-f j-c-b'>
              <View className=''>已兑换{goodsInfo.salesNumber}{goodsInfo.unitName}</View>
              <View className=''>剩余库存{goodsInfo.stockNumber}{goodsInfo.unitName}</View>
            </View>
            <View className='sales-record d-f j-c-b'>
              <AvatarList list={salesReport} showMore/>
              <View className='invite-btn d-f a-i-c bnn-number' hoverClass='hover-class--btn' onClick={this.showShareImg.bind(this)}>
                {goodsInfo.shareAmount ? `分享赚 ${formatAmount(goodsInfo.shareAmount)} 元` : '分享给好友'}
              </View>
            </View>
            {<View className='tip-list d-f f-w-w'>
              {goodsInfo.tips && goodsInfo.tips.map((str, k) => {
                return (<View key={k} className='tip-item d-f a-i-c'>
                  <View className='bnn-icon tip-icon'>&#xe645;</View>
                  <View className='tip-text l-h-o'>{str}</View>
                </View>)
              })}
            </View>}
          </View>
        </View>

        {/* --------------------------------- 拼团 --------------------------------- */}
        {pinkInfo && <View id='goods-group' className='goods-card groups-goods f-g-5 f-d-c'>
          <View className='groups-title'>拼团中，邀请好友一起参与</View>
          <View className='groups-number d-f a-i-c'>
            还差 {pinkInfo.people} 人，距结束<GroupsCountdown seconds={pinkInfo.leftTime} onTimeUp={this.setState.bind(this, { pinkInfo: null })}/>
          </View>
          <View className='groups-user f-g-5 f-w-w'>
            {pinkInfo.partakeList.map((src, key) => {
              return (<View key={key} className='user-info'>
                <Image src={src} className='user-avatar'/>
              </View>)
            })}
          </View>
          {/*<View className='groups-btn f-g-5'>邀请好友参团</View>*/}
          <Button openType='share' className='groups-btn f-g-5' hoverClass='hover-class--btn'>邀请好友参团</Button>
        </View>}

        {/* --------------------------------- 店铺信息 --------------------------------- */}
        {goodsInfo.type === GOODS_TYPE.VIRTUAL && <View className='goods-card goods-card__body shop-card'>
          <View className='goods-card__head'>
            <TitleOne>商家信息</TitleOne>
          </View>
          <ShopInfoOne info={goodsInfo.shopSnap} className='shop-card__head'/>
          <View className='thin-border__b'/>
          <ShopInfoTwo info={goodsInfo.shopSnap} className='shop-card__foot'/>
        </View>}

        {/* --------------------------------- 用户评论 --------------------------------- */}
        {commentRes.list && commentRes.list.length && <View id='goods-comment' className='goods-card goods-card__body comment-card'>
          <View className='goods-card__head'>
            <TitleOne>用户评论</TitleOne>
          </View>
          <View className='comment-list'>
            {commentRes.list.map(info => {
              return (<CommentGoods key={info.id} info={info} className='comment-item'/>)
            })}
            <View className='see-more f-g-5' onClick={() => toCommentGoodsPage(goodsInfo.id)}>查看更多好评（{commentRes.totalCount}）</View>
          </View>
        </View>}

        <View className='goods-body'>
          {/* --------------------------------- 商品详情 --------------------------------- */}
          {goodsInfo.description && <View id='goods-desc' className='goods-card'>
            <View className='goods-card__head'>
              <TitleOne>商品详情</TitleOne>
            </View>
            <View className='rich-text-wrap goods-card__body'>
              <RichText nodes={formatHtml(goodsInfo.description)} />
            </View>
          </View>}

          {/* --------------------------------- 商品推荐 --------------------------------- */}
          <View id='goods-hot' className='goods-card'>
            <View className='goods-card__head'>
              <TitleOne>更多美好生活</TitleOne>
            </View>
            <GoodsOneList list={goodsList}/>
          </View>
        </View>
        <View className='goods-foot--height'/>
      </View>

      <GoodsFoot
        menus={['home', 'share', 'user']}
        onShare={this.showShareImg.bind(this)}>
        {pinkConfig.hasPart && <Button openType='share' className='goods-foot__btns-btn xf-btn xf-btn-primary'>邀请好友来参团</Button>}
        {!pinkConfig.hasPart && !goodsInfo.disabled && <Button
          className='goods-foot__btns-btn goods-foot__cart-btn xf-btn'
          onClick={this.setShowSelect.bind(this, 'buy')}>单独购买</Button>}
        {!pinkConfig.hasPart && <Button
          disabled={goodsInfo.disabled}
          className='goods-foot__btns-btn xf-btn xf-btn-primary'
          onClick={this.setShowSelect.bind(this, 'group')}>{goodsInfo.disabledText || `${pinkConfig.people}人团`}</Button>}
      </GoodsFoot>

      <GroupJoin isOpened={showIsJoin} goodsInfo={goodsInfo} onClose={this.onCloseJoin.bind(this)}/>
      <GoodsSelect goods={goodsInfo} isOpened={showSelect} replacePrice={replacePrice} onClose={this.setState.bind(this, { showSelect: false })} onConfirm={this.onConfirm.bind(this, showSelect)}/>
      <ShareImage isOpened={showShareImg} width={500} height={890} image={shareImg} onClose={this.showShareImg.bind(this, false)}/>
    </View>)
  }
}
